package com.kiven.xml.jaxb;

import java.io.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 创建要转化的java对象，该对象需要使用相关注解注释各字段（标注在get方法上）。
 * 在JAXB标准中，@XmlElementWrapper注解表示生成一个包装 XML 表示形式的包装器元素。
 * 此元素主要用于生成一个包装集合的包装器 XML 元素。因此，该注释支持以下两种形式的序列化。
 * @author kiven
 *
 */

@XmlRootElement
public class Customer2 {
	private String[] names;
	private int age;
	private int id;
	
	// 使用@XmlElementWrapper注释后,将会在原xml节点上再包装一层xml
	@XmlElementWrapper(name="allnames")
	@XmlElement(name="myname")
	public String[] getNames() {
		return names;
	}
	
	public void setNames(String[] names) {
		this.names = names;
	}
	
	@XmlElement
	public int getAge() {
		return age;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	@XmlAttribute
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	@Override
	public String toString() {
		return "Customer [id=" + id +",names=" + names +",age=" + age + "]";
	}
	
	public static void main(String[] args) {
		/**
		 * 此模块代码是讲VO转化为xml文件
		Customer2 customer = new Customer2();
		customer.setId(25);
		customer.setAge(50);
		customer.setNames(new String[] {"kiven","liqingwen","kivenonly"});
		
		try {
			File file = new File("D:\\test.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer2.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.marshal(customer, file);
			jaxbMarshaller.marshal(customer, System.out);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		*/
		
		/**
		 * 将xml文件转化为VO
		 */
		File file = new File("D:\\test.xml");
		JAXBContext jaxbContext;
		try {
			jaxbContext = JAXBContext.newInstance(Customer2.class);
			Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
			
			Customer2 customer = (Customer2)unMarshaller.unmarshal(file);
			System.out.println(customer);
			
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}
}
